﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Turret : MonoBehaviour
{
    public Transform turret_head;
    protected List<GameObject> enemy_list = new List<GameObject>();
    public Transform fire_pos;
    protected Vector3 temp;
    protected float timer = 0;
    public float fire_rate;

    protected void OnTriggerEnter(Collider other)
    {
        if (other.tag == "enemy")
        {
            enemy_list.Add(other.gameObject);
        }
    }
    protected void OnTriggerExit(Collider other)
    {
        if(other.tag == "enemy")
        {
            enemy_list.Remove(other.gameObject);
        }
    }

    protected virtual void Update()
    {
        if (enemy_list.Count > 0)
        {
            if (enemy_list[0] != null)
            {
                timer += Time.deltaTime;
                temp = enemy_list[0].transform.position;
                turret_head.LookAt(new Vector3(temp.x, transform.position.y, temp.z));
                Attack();
            }
            else
            {
                ClearNull();
                timer = fire_rate; //上一个敌人死后能立即发射子弹
            }
        }
    }

    protected virtual void Attack()
    {
        //子类实现
    }

    protected void ClearNull()  //已经死亡的敌人移出列表
    {
        for (int i = 0; i < enemy_list.Count;i++)
        {
            if (enemy_list[i] == null)
            {
                enemy_list.Remove(enemy_list[i]);
                i--;
            }
        }
    }
}
